package cn.dvptech.remotecontrol.screenmirror.sender;

import java.io.BufferedOutputStream;
import java.io.IOException;
import cn.dvptech.remotecontrol.screenmirror.screenHelper.Frame;
import cn.dvptech.remotecontrol.screenmirror.sender.packets.Video;
import timber.log.Timber;

/**
 *    author  : ulongx
 *    website : www.dvptech.cn
 *    date    : 2024/7/20
 *    desc    :
 */
public class TcpWriteThread extends Thread {
    private BufferedOutputStream bos;
    private ISendQueue iSendQueue;
    private volatile boolean startFlag;
    private OnTcpWriteListener mListener;

    public TcpWriteThread(BufferedOutputStream bos, ISendQueue sendQueue, OnTcpWriteListener listener) {
        this.bos = bos;
        startFlag = true;
        this.iSendQueue = sendQueue;
        this.mListener = listener;
    }

    @Override
    public void run() {
        super.run();
        while (startFlag) {
            Frame frame = iSendQueue.takeFrame();
            if (frame == null) {
                continue;
            }
            if (frame.data instanceof Video) {
                sendData(((Video) frame.data).getContent());
            }
            if (frame.data instanceof String){
                sendMessage((String) frame.data);
                Timber.d("send a msg: %s", (String) frame.data);
            }
        }
    }


    public void shutDown() {
        startFlag = false;
        this.interrupt();
    }

    public void sendData(byte[] buff) {
        try {
            MessageEncoder encode = new MessageEncoder(buff);
            bos.write(encode.buildSendContent(MessageEncoder.MessageType.VIDEO));
            bos.flush();
        } catch (IOException e) {
            startFlag = false;
            mListener.socketDisconnect();
        }
    }

    public void sendMessage(String message) {
        try {
            MessageEncoder encode = new MessageEncoder(message.getBytes());
            bos.write(encode.buildSendContent(MessageEncoder.MessageType.TEXT));
            bos.flush();
        } catch (IOException e) {
            startFlag = false;
            mListener.socketDisconnect();
        }
    }

}
